package com.one.rope.mvp.basecore.util;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.*;

/**
 * @author Weijian.liu
 * @desc Http请求工具类
 * @date 2019/1/15
 */
public class HttpRequestUtil {

  private static Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);

  private static PoolingHttpClientConnectionManager connectionManager = null;
  private static HttpClientBuilder httpBuilder = null;
  private static RequestConfig requestConfig = null;
  private static int MAXCONNECTION = 10;
  private static int DEFAULTMAXCONNECTION = 5;

  static {
    //设置http的状态参数
    requestConfig = RequestConfig.custom()
        .setSocketTimeout(5000)
        .setConnectTimeout(5000)
        .setConnectionRequestTimeout(5000)
        .build();
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(MAXCONNECTION);//客户端总并行链接最大数
    connectionManager.setDefaultMaxPerRoute(DEFAULTMAXCONNECTION);//每个主机的最大并行链接数
    httpBuilder = HttpClients.custom();
    httpBuilder.setConnectionManager(connectionManager);
  }

  /**
   * 发送get请求
   *
   * @param url 请求url
   * @param paramMap 请求参数
   */
  public static String sendGetRequest(String url, Map<String, String> paramMap) {
    HttpResponse httpResponse = null;
    HttpClient httpClient = null;
    String responseResult = null;
    try {
      httpClient = getConnection();
      URIBuilder uriBuilder = new URIBuilder(url);
      List<NameValuePair> params = new ArrayList<>();
      Set<Map.Entry<String, String>> entrySet = paramMap.entrySet();
      for (Map.Entry<String, String> e : entrySet) {
        String name = e.getKey();
        String value = e.getValue();
        NameValuePair pair = new BasicNameValuePair(name, value);
        params.add(pair);
      }
      uriBuilder.setParameters(params);
      HttpGet httpGet = new HttpGet(uriBuilder.build());
      httpResponse = httpClient.execute(httpGet);
      responseResult = EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
      logger.error(e.getMessage());
    } catch (ParseException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (Exception e) {
      logger.error(e.getMessage());
    } finally {
      // 关闭连接,释放资源
    }
    return responseResult;
  }

  /**
   * 发送post请求/请求参数为json
   *
   * @param url 请求url
   * @param param 请求参数
   */
  public static String sendPostRequest(String url, JSONObject param) {
    HttpResponse httpResponse = null;
    HttpClient httpClient = null;
    String responseResult = null;
    try {
      httpClient = getConnection();
      HttpPost httpPost = new HttpPost(url);
      StringEntity stringEntity = new StringEntity(param.toString(), "UTF-8");
      stringEntity.setContentEncoding("UTF-8");
      stringEntity.setContentType("application/json");
      httpPost.setEntity(stringEntity);
      httpResponse = httpClient.execute(httpPost);
      responseResult = EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
      logger.error(e.getMessage());
    } catch (ParseException e) {
      logger.error(e.getMessage());
    } catch (IOException e) {
      logger.error(e.getMessage());
    } catch (Exception e) {
      logger.error(e.getMessage());
    } finally {
      // 关闭连接,释放资源
    }
    return responseResult;
  }

  /**
   * 获取请求连接
   */
  public static CloseableHttpClient getConnection() {
    CloseableHttpClient httpClient = httpBuilder.build();
    return httpClient;
  }

  public static void main(String[] args) throws Exception {
    String url = "https://qyapi.weixin.decrypt.com/cgi-bin/department/create?access_token=" +
        "Wj0yIAWARZkS_h8LoxsCjmQKGjT3jT2XreK38Z-juoTgkaF8tG93yx7i03LmCpC4H4uAT7IHSIPUwgwzhrDRomccnvnzVvkVk9HERE1knMvuTEQexsFhg2m6a96xup2W1DBEms3HlqwB54mOme5YYp4nXkHSYBT_74X9dL9lYpK1j5kggAlbuVQ4vHYNpi4Mwv1edTXu3qtgUjHBG_Hf-Q";
    //?corpid=ID&corpsecret=SECRECT"
    JSONObject json = new JSONObject();
    json.put("name", "test232");
    json.put("parentid", "85");
    String response = sendPostRequest(url, json);
    System.out.println("返回实体内容==" + response);

  }
}
